package com.fw.dao.impl;

import java.util.List;

import com.fw.dao.PermissionDao;
import com.fw.model.Permission;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class PermissionDaoImpl implements PermissionDao {

	@Override
	public Integer query_totalPermisssonDao(String sql) {
		String s = "select count(*) from permission p where 1 = 1 "+sql;
		long count = Db.queryLong(s);
		return (int) count;
	}

	@Override
	public List<Permission> query_allPermissonByPageDao(String sql,int firstPage, int maxPage) {
		String s = "select * from permission p  where 1 = 1 limit ?,?";
		List<Permission> ps = Permission.permissonDao.find(s,firstPage,maxPage);
		if(ps.size()>0) return ps;
		return null;
	}

	@Override
	public boolean add_permissionDao(Permission permisson) {
		return permisson.save();
	}

	@Override
	public Permission query_permissionByName(Permission permission) {
		String sql = "select * from permission p where p.p_name = ?";
		List<Permission> ps = Permission.permissonDao.find(sql, permission.getStr("p_name"));
		if(ps.size() > 0) return ps.get(0);
		return null;
	}

	@Override
	public List<Permission> query_permissionForTypeDao(Permission permission) {
		String sql = "select * from permission p where p.p_url is ? and p.parent_id is ?";
		List<Permission> ps = Permission.permissonDao.find(sql, null,null);
		return ps;
	}

	@Override
	public Permission query_permissionByIdDao(Permission permission) {
		String sql = "select * from permission p where p.p_id = ?";
		List<Permission> ps = Permission.permissonDao.find(sql,permission.getInt("p_id"));
		if(ps.size()>0) return ps.get(0);
		return null;
	}

	@Override
	public boolean update_permissionByIdDao(Permission permission) {
		Record r = Db.findById("permission", "p_id", permission.getInt("p_id"))
				   .set("p_name", permission.getStr("p_name"))
				   .set("p_url", permission.getStr("p_url"))
				   .set("parent_id", permission.getInt("parent_id"));
		return Db.update("permission","p_id",r);
	}

	@Override
	public boolean delete_permissionByIdDao(Permission permission) {
		return Db.deleteById("permission", "p_id", permission.getInt("p_id"));
	}

}
